package phase1.part3;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import phase1.part3.InputFileReader.FileFormatException;

/**
 * 
 * 
 * @author John Girata
 * @version Nov 1, 2012
 */
public class TableWalker {
	private static final Logger LOG;

	private State start;
	private List<Token> tokens;

	private State current;
	private boolean fresh;
	private String runningToken;
	private Token lastAccepted;

	static {
		LOG = Logger.getLogger("phase1.part3.TableWalker");
	}

	public TableWalker(String filename) throws FileNotFoundException,
			FileFormatException {
		InputFileReader file = new InputFileReader(filename);
		start = file.getStart();
		tokens = new ArrayList<>();

		reset();
	}

	private final void reset() {
		current = start;
		fresh = true;
		lastAccepted = null;
		runningToken = "";
	}

	public List<Token> process(String input) {
		for (char c : input.toCharArray()) {
			process(c);
		}
		
		process('\0');

		return tokens;
	}

	public void process(char next) {
		for (Transition t : current.getTransitions()) {
			if (t.getPattern().accepts(next)) {
				advance(next, t);
				return;
			}
		}

		if (!fresh) {
			LOG.info("Adding token " + lastAccepted);
			tokens.add(lastAccepted);
			reset();
			process(next);
		}
	}

	private void advance(char next, Transition t) {
		fresh = false;
		current = t.getEnd();
		runningToken += next;

		if (current.isAccepting()) {
			lastAccepted = new Token(runningToken, current.getTokenClass());
		}
	}
}
